#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "key.h"
#include "esp_log.h"


static const char *TAG = "Key";
EventGroupHandle_t key_event_group;

void key_task(void *pvParameters);

void key_init()
{
    gpio_reset_pin(KEY_PIN);
    gpio_set_direction(KEY_PIN, GPIO_MODE_INPUT);
    gpio_set_pull_mode(KEY_PIN, GPIO_PULLUP_ONLY);

    // 创建事件标志组
    key_event_group = xEventGroupCreate();
    // 创建按键任务
    xTaskCreate(key_task, "key_task", 2048, NULL, 5, NULL);
}

KeyState key_get_state()
{
    return gpio_get_level(KEY_PIN) == 0 ? KEY_PRESSED : KEY_RELEASED;
}

void key_task(void *pvParameters)
{
    KeyState prevKeyState = key_get_state();
    KeyState currKeyState;

    TickType_t pressStartTime = 0;
    bool longPressTriggered = false;

    while (1)
    {
        currKeyState = key_get_state();

        if (currKeyState != prevKeyState)
        {
            if (currKeyState == KEY_RELEASED)
            {
                if (longPressTriggered)
                {
                    ESP_LOGI(TAG, "Key released (long press)");
                }
                else
                {
                    ESP_LOGI(TAG, "Key released (short press)");
                    xEventGroupSetBits(key_event_group, SHORT_PRESS_EVENT_BIT);
                }
                longPressTriggered = false;
            }
            else
            {
                pressStartTime = xTaskGetTickCount();
            }
        }
        else if (currKeyState == KEY_PRESSED && !longPressTriggered)
        {
            TickType_t elapsedTime = xTaskGetTickCount() - pressStartTime;
            if (elapsedTime >= pdMS_TO_TICKS(LONG_PRESS_DURATION))
            {
                ESP_LOGI(TAG, "Key pressed (long press)");
                xEventGroupSetBits(key_event_group, LONG_PRESS_EVENT_BIT);
                longPressTriggered = true;
            }
        }

        prevKeyState = currKeyState;
        vTaskDelay(10 / portTICK_PERIOD_MS);
    }
}